/**
 * 
 */
package com.wisdytech.linkdcs.equipment.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.github.pagehelper.PageInfo;
import com.wisdytech.common.bean.Filter;
import com.wisdytech.common.bean.StandardResult;
import com.wisdytech.common.bean.event.DcsParamChangeEvent;
import com.wisdytech.common.constants.CommonConstants;
import com.wisdytech.common.enums.ActionType;
import com.wisdytech.common.exception.ServiceException;
import com.wisdytech.common.handler.BaseService;
import com.wisdytech.common.thrift.service.IEquipmentCollectionInfoService;
import com.wisdytech.common.utils.EquipmentKeyUtils;
import com.wisdytech.linkdcs.equipment.dao.IEqCollectionClientDao;
import com.wisdytech.linkdcs.equipment.dao.IEqCollectionParamDao;
import com.wisdytech.linkdcs.equipment.dao.IEqEquipAlarmParamDao;
import com.wisdytech.linkdcs.equipment.dao.IEqEquipmentDao;
import com.wisdytech.linkdcs.equipment.dao.IEqModelDao;
import com.wisdytech.linkdcs.equipment.model.CollectionClient;
import com.wisdytech.linkdcs.equipment.model.CollectionParam;
import com.wisdytech.linkdcs.equipment.model.EquipAlarmParam;
import com.wisdytech.linkdcs.equipment.model.EquipModel;
import com.wisdytech.linkdcs.equipment.model.Equipment;
import com.wisdytech.linkdcs.equipment.service.IEquipmentParamService;

/**
 * <p>
 * ClassName: EquipmentParamServiceImpl
 * </p>
 * <p>
 * Description: 参数管理业务层
 * </p>
 * <p>
 * Author: kongming
 * </p>
 * <p>
 * Date: 2017-9-26
 * </p>
 */
@Service("equipmentParamService")
@Transactional
public class EquipmentParamServiceImpl extends BaseService<IEqCollectionParamDao, CollectionParam> implements IEquipmentParamService {
    
	/**
     * 注入eqCollectionParamDao
     */
    @Resource
    private IEqCollectionParamDao eqCollectionParamDao;
    /**
     * 注入eqModelDao
     */
    @Resource
    private IEqModelDao eqModelDao;
    /**
     * 注入eqCollectionClientDao
     */
    @Resource
    private IEqCollectionClientDao eqCollectionClientDao;
    /**
     * 注入告警dao
     */
    @Resource
    private IEqEquipAlarmParamDao alarmParamDao;
    
    @Resource
    private IEqEquipmentDao equipmentDao;
    
    /**处理设备注册事件推送*/
    @Autowired
    ApplicationContext applicationContext;
    
    
    @Override
    public PageInfo<CollectionParam> listParamByFilter(String modelCode, String modelType, String paramName, Filter filter) {
        Map<String, Object> queryMap;
        queryMap = new HashMap<String, Object>();
        queryMap.put("modelCode", modelCode);
        queryMap.put("modelType", modelType);
        queryMap.put("paramName", paramName);
        List<CollectionParam> lists =
                super.beforeList(IEqCollectionParamDao.class, filter).selectParamPage(queryMap);
        PageInfo<CollectionParam> equipModelPage=new PageInfo<>(lists);
        return equipModelPage;
    }

    @Override
    public StandardResult addCollectionParam(CollectionParam param, String loginName) {
        EquipModel model = new EquipModel();
        model = eqModelDao.getEuipmentModelByEmModel(param.getModelCode());
        CollectionClient client = new CollectionClient();
        client = eqCollectionClientDao.getCollectionClientByModelId(param.getModelCode());
        param.setCollectionClientId(client.getPkId());
        param.setOperationId(param.getOperationName());
        
        EntityWrapper<CollectionParam> ew = new EntityWrapper<>();
        List<CollectionParam> paramList;
        paramList = eqCollectionParamDao.selectPage(new Page<CollectionParam>(1, 1), ew.eq("PARAM_CODE", param.getParamCode()).eq("del_flag", CommonConstants.DEL_FLAG));
        
        if (!paramList.isEmpty()) {
            return StandardResult.getFailResult("参数编号已存在");
        }
        //通过规则获取参数的唯一id
        
        String pkId =
        		EquipmentKeyUtils.getParamKey(model.getModelCode(), param);
        CollectionParam uParam =eqCollectionParamDao.selectById(pkId);
        if(null!=uParam) {//唯一id存在，同一型号下参数地址已存在，不允许删除
        	throw new ServiceException("参数地址已存在！！！");
        }
        param.setPkId(pkId);

        param.setDelFlag(CommonConstants.DEL_FLAG);
        param.setCreateUser(loginName);
        param.setCreateDate(new Date());
        int paramCount = eqCollectionParamDao.insert(param);
        if (paramCount <=0) {
            throw new ServiceException("新增失败");
        }
        
        //推送设备参数到dcs
//        处理推送
        DcsParamChangeEvent changeEvent =new DcsParamChangeEvent(this,ActionType.ADD,param,param.getCollectionClientId());
        applicationContext.publishEvent(changeEvent); 
        

        return StandardResult.getSuccessResult();
    }

    @Override
    public StandardResult delCollectionParam(String id) {
    	//参数删除推送事件对象
    	List<CollectionParam> paramChangeParams=new ArrayList<>();
    	
        List<String> idList = new ArrayList<String>();
        String[] ids = id.split(",");
        for (int i = 0; i < ids.length; i++) {
            idList.add(ids[i]);
        }
        
        
        for (String pkId : ids) {
        
        	CollectionParam param  =  eqCollectionParamDao.selectById(pkId);
        	paramChangeParams.add(param);
        	
            EntityWrapper<EquipAlarmParam> ew = new EntityWrapper<>();
            List<EquipAlarmParam> alarmParamList = alarmParamDao.selectList(ew.eq("PARAM_ID", param.getPkId()).eq("DEL_FLAG", 0));
            if (!alarmParamList.isEmpty()) {
                return StandardResult.getFailResult(CommonConstants.EQUIPMENT_ALARM_PARAM);
            }
            //0--代表参数没有可视化管理设置--可以删除
            if ("0".equals(param.getShowLevel())) {
                int count = eqCollectionParamDao.deleteById(pkId);
                if (count <= 0){
                        throw new ServiceException("删除失败");
                }
            }else {
                return StandardResult.getFailResult(CommonConstants.PARAM_SHOWLEVEL);
            }
        }
        
        //推送设备参数到dcs
        //顺序推送删除参数
        for(CollectionParam paramChange : paramChangeParams) {
        	DcsParamChangeEvent changeEvent =new DcsParamChangeEvent(
        			this,ActionType.ADD,paramChange,paramChange.getCollectionClientId());
            applicationContext.publishEvent(changeEvent); 
        }
        
        
        return StandardResult.getSuccessResult();
    }

    @Override
    public StandardResult updateCollectionParam(CollectionParam param, String loginName) {
        EquipModel model = new EquipModel();
        model = eqModelDao.getEuipmentModelByEmModel(param.getModelCode());
        CollectionClient client = new CollectionClient();
        client = eqCollectionClientDao.getCollectionClientByModelId(model.getModelCode());
        
        
        EntityWrapper<CollectionParam> ew = new EntityWrapper<>();
        List<CollectionParam> paramList;
        paramList = eqCollectionParamDao.selectPage(new Page<CollectionParam>(1, 1), ew.eq("PARAM_CODE", param.getParamCode()).ne("pk_id", param.getPkId()).eq("del_flag", CommonConstants.DEL_FLAG));
        
        if (!paramList.isEmpty()) {
            return StandardResult.getFailResult("参数编号已存在");
        }
        param.setCollectionClientId(client.getPkId());
        param.setOperationId(param.getOperationName());
        param.setUpdateUser(loginName);
        param.setUpdateDate(new Date());
        int count = eqCollectionParamDao.updateById(param);
        if (count <= 0) {
            throw new ServiceException("修改失败");
        }
        
        //推送设备参数到dcs
        //查找最新的参数记录
        CollectionParam  nParam=eqCollectionParamDao.selectById(param.getPkId());
        DcsParamChangeEvent changeEvent =new DcsParamChangeEvent(this,ActionType.UPDATE,nParam,nParam.getCollectionClientId());
        applicationContext.publishEvent(changeEvent); 
        
        return StandardResult.getSuccessResult();
    }

    @Override
    public CollectionParam getEuipmentParamById(String pkId) {
        return eqCollectionParamDao.selectById(pkId);
    }

    @Override
    public List<CollectionParam> listModelParams(String modelId) {
       
        return eqCollectionParamDao.selectParamByModelId(modelId);
        
    }
    
    @Override
    public List<CollectionParam> listModelParamsByModelCode(String modelCode) {
       
        return eqCollectionParamDao.selectParamByModelCode(modelCode);
        
    }
    
    

    @Override
    public List<CollectionParam> listEqParams(String eqCode) {
        
        return eqCollectionParamDao.selectParamByEqCode(eqCode,"","");
    }

	@Override
	public List<CollectionParam> listModelParams(String modelId,
			String paramName, int page, int size) {
		Filter filter =new Filter();
		filter.setNum(page);
		filter.setSize(size);
		
		List<CollectionParam>  params =beforeList(IEqCollectionParamDao.class, filter).
			selectParamByModelIdAndName(modelId, paramName);
		
		
		return params;
	}

	@Override
	public PageInfo<CollectionParam> listParams(String eqCode,String search, Filter filter) {
		
		List<CollectionParam>  params =this.beforeList(IEqCollectionParamDao.class, filter).selectParamByEqCode(eqCode,search,"5");
		
		return new PageInfo<CollectionParam>(params);
	}

	
}
